package com.asktgapp.hxsg;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.FileProvider;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.application.MyApplication;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.dialog.CProgressDialogUtils;
import com.asktgapp.dialog.ConfirmEndChatDialog;
import com.asktgapp.dialog.HomeServiceDialog;
import com.asktgapp.dialog.YaoQingPJDialog;
import com.asktgapp.model.EvaluateVO;
import com.asktgapp.modulebase.Constant;
import com.asktgapp.modulebase.ServiceUtil;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.modulebase.common.widget.loading.LoadingDialogFragment;
import com.asktgapp.user.activity.ComplaintEngineerActivity;
import com.asktgapp.user.activity.EngineerDetailActivity;
import com.asktgapp.user.activity.MainActivity;
import com.asktgapp.user.activity.PayActivity;
import com.asktgapp.utils.CustomPopWindow;
import com.hyphenate.EMChatRoomChangeListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessage.ChatType;
import com.hyphenate.chat.EMMucSharedFile;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.EaseUI;

import com.hyphenate.easeui.domain.EaseEmojicon;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.model.EaseAtMessageHelper;
import com.hyphenate.easeui.ui.EaseBaiduMapActivity;
import com.hyphenate.easeui.ui.EaseBaseFragment;
import com.hyphenate.easeui.ui.EaseGroupRemoveListener;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.utils.EaseUserUtils;
import com.hyphenate.easeui.widget.EaseAlertDialog;
import com.hyphenate.easeui.widget.EaseAlertDialog.AlertDialogUser;
import com.hyphenate.easeui.widget.EaseChatExtendMenu;
import com.hyphenate.easeui.widget.EaseChatInputMenu;
import com.hyphenate.easeui.widget.EaseChatInputMenu.ChatInputMenuListener;
import com.hyphenate.easeui.widget.EaseChatMessageList;
import com.hyphenate.easeui.widget.EaseVoiceRecorderView;
import com.hyphenate.easeui.widget.EaseVoiceRecorderView.EaseVoiceRecorderCallback;
import com.hyphenate.easeui.widget.JGPingJia;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.hyphenate.util.EMLog;
import com.hyphenate.util.PathUtil;
import com.sobot.chat.utils.ToastUtil;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * you can new an EaseChatFragment to use or you can inherit it to expand.
 * You need call setArguments to pass chatType and userId
 * <br/>
 * <br/>
 * you can see ChatActivity in demo for your reference
 */
public class EaseChatFragment extends EaseBaseFragment implements EMMessageListener {
    protected static final String TAG = "EaseChatFragment";
    protected static final int REQUEST_CODE_MAP = 1;
    protected static final int REQUEST_CODE_CAMERA = 2;
    protected static final int REQUEST_CODE_LOCAL = 3;

    private OnSendMessageListener onSendMessageListener;

    public void setOnSendMessageListener(OnSendMessageListener onSendMessageListener) {
        this.onSendMessageListener = onSendMessageListener;
    }

    /**
     * params to fragment
     */
    protected Bundle fragmentArgs;
    protected int chatType;
    protected String toChatLocalUsername;
    protected String toChatUsername;
    protected EaseChatMessageList messageList;
    protected EaseChatInputMenu inputMenu;

    protected EMConversation conversation;

    protected InputMethodManager inputManager;
    protected ClipboardManager clipboard;

    protected Handler handler = new Handler();
    protected File cameraFile;
    protected EaseVoiceRecorderView voiceRecorderView;
    protected SwipeRefreshLayout swipeRefreshLayout;
    protected ListView listView;

    protected boolean isloading;
    protected boolean haveMoreData = true;
    protected int pagesize = 20;
    protected GroupListener groupListener;
    protected EMMessage contextMenuMessage;

    static final int ITEM_TAKE_PICTURE = 1;
    static final int ITEM_PICTURE = 2;
    static final int ITEM_LOCATION = 3;
    private static final int ITEM_VIDEO = 11;
    protected int[] itemStrings = {R.string.attach_take_pic, R.string.attach_picture};//, R.string.attach_location
    protected int[] itemdrawables = {R.drawable.ease_chat_takepic_selector, R.drawable.ease_chat_image_selector};
    //,R.drawable.ease_chat_location_selector
    protected int[] itemIds = {ITEM_TAKE_PICTURE, ITEM_PICTURE};//, ITEM_LOCATION
    private EMChatRoomChangeListener chatRoomChangeListener;
    private boolean isMessageListInited;
    protected MyItemClickListener extendMenuItemClickListener;
    private int type;
    private String cid;
    private String toUserid;
    private TextView mAskAgainTV;
    private JGPingJia mJGPingJia;
    private EvaluateVO mEvaluateVO;
    private int mAskType;
    private double mMoney;
    private String toHeadImg;
    private TextView mWaitForPJ, pingJia;
    //    private TextView mTip;
    private CustomPopWindow popWindow;
    /**
     * 当前真正发送的消息
     */
    public String messageHasSendCur = "";

    public String messageResult = "";


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.ease_fragment_chat, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        fragmentArgs = getArguments();
        // check if single chat or group chat
        chatType = fragmentArgs.getInt(EaseConstant.EXTRA_CHAT_TYPE,1);
        // userId you are chat with or group id
        toChatUsername = fragmentArgs.getString(EaseConstant.EXTRA_USER_ID);
        toChatLocalUsername = fragmentArgs.getString("jg_username");
        type = fragmentArgs.getInt("type");
        cid = fragmentArgs.getString("cid");
        toUserid = fragmentArgs.getString("toUserId");
        mAskType = fragmentArgs.getInt("askType");
        toHeadImg = fragmentArgs.getString("headimg");
        super.onActivityCreated(savedInstanceState);
    }


    /**
     * init view
     */
    protected void initView() {
        // hold to record voice
        //noinspection ConstantConditions
        mAskAgainTV = getView().findViewById(R.id.tv_ask_again);
        mJGPingJia = getView().findViewById(R.id.jg_pj);
        mWaitForPJ = getView().findViewById(R.id.tv_wait_pj);
        pingJia = (TextView) getView().findViewById(R.id.pingJia);
        voiceRecorderView = (EaseVoiceRecorderView) getView().findViewById(R.id.voice_recorder);
//        mTip = getView().findViewById(R.id.tip);
        // message list layout
        messageList = (EaseChatMessageList) getView().findViewById(R.id.message_list);
        if (chatType != EaseConstant.CHATTYPE_SINGLE)
            messageList.setShowUserNick(true);
        listView = messageList.getListView();

        extendMenuItemClickListener = new MyItemClickListener();
        inputMenu = (EaseChatInputMenu) getView().findViewById(R.id.input_menu);
        registerExtendMenuItem();
        // init input menu
        inputMenu.init(null);
        inputMenu.setChatInputMenuListener(new ChatInputMenuListener() {

            @Override
            public void onTyping(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void onSendMessage(String content) {
                messageResult = content;
                sendTextMessage(content);
                onSendMessageListener.onSendTextMessage(content);
            }

            @Override
            public boolean onPressToSpeakBtnTouch(View v, MotionEvent event) {
                return voiceRecorderView.onPressToSpeakBtnTouch(v, event, new EaseVoiceRecorderCallback() {

                    @Override
                    public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
                        sendVoiceMessage(voiceFilePath, voiceTimeLength);
                        onSendMessageListener.onSendVoiceMessage("[语音]");
                        messageResult = "[语音]";
                    }
                });
            }

            @Override
            public void onBigExpressionClicked(EaseEmojicon emojicon) {
                sendBigExpressionMessage(emojicon.getName(), emojicon.getIdentityCode());
                onSendMessageListener.onSendBigEmoj("大表情[" + emojicon.getName() + "]");
                messageResult = "大表情[" + emojicon.getName() + "]";
            }
        });

        /**
         * type
         * 0：普通用户咨询（允许输入）
         * 1：普通用户已经结束（进来看看或者评价）（can't chat）
         * 2：工程师（允许输入）
         * 3:工程师 已结束（进来看评价）(can't chat)
         */
//        if (type == 1 || type == 0) {
//            mTip.setVisibility(View.VISIBLE);
//        } else mTip.setVisibility(View.GONE);
        if (type == 1 || type == 3) {
            //不可聊天type ,屏蔽掉输入框

            inputMenu.setVisibility(View.GONE);
            if (!PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER)) {

            }
        } else {
            //可聊天type ,显示输入框
            inputMenu.setVisibility(View.VISIBLE);
            if (!PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER)) {
                int num = PreferencesUtil.getInt(getActivity(), cid + "User", 0);
                if (num == 0) {
                    HomeServiceDialog dialog = new HomeServiceDialog("感谢咨询！24小时内工程师将为您详细解答问题，如回复有延迟请耐心等待！",
                            "知道了", new HomeServiceDialog.onResultCallBack() {
                        @Override
                        public void onSure() {

                        }
                    });
                    dialog.show(getFragmentManager(), "HomeServiceDialog");
                    PreferencesUtil.putInt(getActivity(), cid + "User", 1);
                }

            }
        }
        getPingJia();
        swipeRefreshLayout = messageList.getSwipeRefreshLayout();
        swipeRefreshLayout.setColorSchemeResources(R.color.btn_blue_pressed);

        inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);


    }

    private void getPingJia() {
        final Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        params.put("id", toUserid);
        if (type == 0 || type == 1) {
            //不是工程师
            params.put("type", 0);
        } else {
            //是工程师
            params.put("type", 1);
        }
        params.put("cid", cid);
        Call<ApiResponseBody<EvaluateVO>> call = apiservice.getEvaluate(params);
        call.enqueue(new Callback<ApiResponseBody<EvaluateVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<EvaluateVO>> call, Response<ApiResponseBody<EvaluateVO>> response) {
                if (response.isSuccessful()) {
                    mEvaluateVO = response.body().getResult();
                    setUI(mEvaluateVO);
                } else {
                    Toast.makeText(getActivity(), response.raw().message(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<EvaluateVO>> call, Throwable t) {
                ApiException apiException = ExceptionHandle.handleException(t);
                Toast.makeText(getActivity(), apiException.getMessage(), Toast.LENGTH_SHORT).show();
                if (apiException.getErrorCode() == 10004) {
                    Toast.makeText(getActivity(), apiException.getMessage(), Toast.LENGTH_SHORT).show();
                    getActivity().finish();
                }
            }
        });

    }

    private void evaluate(final int i, final int j, final int k, final String content) {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();

        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        params.put("bp_user_id", toUserid);
        params.put("satisfaction", i);
        params.put("attitude", j);
        params.put("quality", j);
        params.put("speed", k);
        params.put("content", content);
        if (!com.asktgapp.JGTool.Utils.noContainsEmoji(content)) {
            Toast.makeText(getActivity(), "不支持输入emoji表情", Toast.LENGTH_SHORT).show();
            return;
        }
        params.put("cid", cid);
//        showProgress(getClass().getSimpleName());
        CProgressDialogUtils.showProgressDialog(getActivity());
        Call<ApiResponseBody> call = apiservice.evaluate(params);
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                CProgressDialogUtils.cancelProgressDialog();
                if (response.isSuccessful()) {
                    Toast.makeText(getActivity(), "评价成功，感谢您的支持！", Toast.LENGTH_SHORT).show();
                    mJGPingJia.setPJUser("", j, k, content);
                    mWaitForPJ.setText("  您已评价过本次服务 ");
                    pingJia.setText("查看评价");
                    EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD);
                    String action = "已评价";//action可以自定义
                    EMCmdMessageBody cmdBody = new EMCmdMessageBody(action);
                    String toUsername = toChatUsername;//发送给某个人
                    cmdMsg.setTo(toUsername);
                    cmdMsg.addBody(cmdBody);
                    EMClient.getInstance().chatManager().sendMessage(cmdMsg);
                    endChat();
                } else {
                    //// TODO: 2018/3/6 提交评价
                    showChatroomToast(response.raw().message());
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                CProgressDialogUtils.cancelProgressDialog();
                ApiException apiException = ExceptionHandle.handleException(t);
                showChatroomToast(apiException.getMessage());
            }
        });
    }

    public void openInput() {
        inputMenu.setVisibility(View.VISIBLE);
    }

    public void closeInput() {
        inputMenu.setVisibility(View.GONE);
    }


    private void setUI(EvaluateVO bean) {
//        if (bean.getIs_end() == 0 && bean.getIs_engineer() == 0) {
//            //未结束，不是工程师
//            if (type == 0 || type == 1) {
//                //普通用户进来的时候，说明咨询的工程师已经注销掉了工程师身份
//                Toast.makeText(getActivity(), "咨询中的工程师已注销，不能进行咨询，如有疑问，请联系客服或在意见反馈中留言！", Toast.LENGTH_LONG).show();
//                getActivity().finish();
//                return;
//            }
//        }
        mAskType = bean.getType();
        //////////////////////////
        if (type == 0) {
            if (bean.getIs_end() == 1) {
                type = 1;//由于从推送近来无法判断是否已经结束，传的是0，表示用户，传的2表示工程师
            }
        } else if (type == 2) {
            if (bean.getIs_end() == 1) {
                type = 3;
            }
        }
        //////////////////////////////弥补从推送进入时的参数
        if (type == 0 || type == 2) {
            //未结束的时候
            mJGPingJia.setVisibility(View.GONE);
        } else {
            if (type == 1) {
//                evaluateLable();
                //用户已结束点进来
                inputMenu.setVisibility(View.GONE);
                //未评价过，初始化评价面板
                mWaitForPJ.setText("  服务时间已到，已经自动结束，请你评价本次服务 ");
                mWaitForPJ.setVisibility(View.VISIBLE);
                pingJia.setVisibility(View.VISIBLE);
                pingJia.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mJGPingJia.getVisibility() == View.VISIBLE) {
                            mJGPingJia.setVisibility(View.GONE);
                        } else {
                            mJGPingJia.setVisibility(View.VISIBLE);
                        }
                    }
                });

                mAskAgainTV.setVisibility(View.VISIBLE);
                //0 立即咨询 1二手机评估 2故障代检
                Resources resources = getActivity().getResources();
                String str = "再次咨询";
                if (mAskType == 0) {
                    mMoney = bean.getAdvisory_price();
                    str = String.format(resources.getString(com.asktgapp.R.string.ask_again_price)
                            , com.asktgapp.JGTool.Utils.D2S(bean.getAdvisory_price()));
                } else if (mAskType == 1) {
                    mMoney = bean.getEvaluation_price();
                    str = String.format(resources.getString(com.asktgapp.R.string.ask_again_price)
                            , com.asktgapp.JGTool.Utils.D2S(bean.getEvaluation_price()));
                } else if (mAskType == 2) {
                    mMoney = bean.getDetection_price();
                    str = String.format(resources.getString(com.asktgapp.R.string.ask_again_price)
                            , com.asktgapp.JGTool.Utils.D2S(bean.getDetection_price()));
                }
                mAskAgainTV.setText(str);
                mAskAgainTV.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        askAgiagn();

                    }
                });
                if (bean.getIs_evaluate() == 0) {

                    mJGPingJia.setOnCommitListener(new JGPingJia.onCommit() {
                        @Override
                        public void onCommit(int i, int j, int k, String content) {
                            if (TextUtils.isEmpty(content))
                                content = "用户没有输入任何内容";
                            evaluate(i, j, k, content);
                        }
                    });

                } else {
                    clickPJITem = false;
                    mWaitForPJ.setText("  您已评价过本次服务 ");
                    pingJia.setText("查看评价");
                    pingJia.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (pingJia.getText().toString().equals("查看评价")) {
                                mJGPingJia.setVisibility(View.VISIBLE);
                                pingJia.setText("收起评价");
                            } else {
                                mJGPingJia.setVisibility(View.GONE);
                                pingJia.setText("查看评价");
                            }
                        }
                    });
                    //用户评价过，设置评价面板
                    mJGPingJia.setPJUser(bean.getEvaluateAnswerContent(), bean.getQuality(), bean.getSpeed(), bean.getContent());

                }
            } else {
                if (!TextUtils.isEmpty(cid))
                    PreferencesUtil.putBoolean(getActivity(), cid, false);
                //工程师点进来
                mWaitForPJ.setVisibility(View.VISIBLE);
                inputMenu.setVisibility(View.GONE);
                titleBar.setRightLayoutVisibility(View.GONE);
                if (bean.getIs_evaluate() == 0) {
                    mJGPingJia.setVisibility(View.GONE);
                    //未评价过，展示"服务已结束，等待用户打分评价"
                } else {
                    evaluateId = bean.getEvaluateId();
                    mWaitForPJ.setVisibility(View.GONE);
                    //评价过，展示评价面板
                    mJGPingJia.setVisibility(View.VISIBLE);
                    mJGPingJia.setPJEngineer(bean.getEvaluateAnswerContent(), bean.getQuality(), bean.getSpeed(), bean.getContent());

                    mJGPingJia.setOnCommitListener(new JGPingJia.onCommit() {
                        @Override
                        public void onCommit(int i, int j, int k, String content) {
                            if (i == -1) {
                                replyEvaluate(content);
                            }

                        }
                    });
                }
            }

        }

    }

    private void sendSMS() {
        if (TextUtils.isEmpty(cid))
            cid = "sendSMS";
        if (PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER)) {
            if (!PreferencesUtil.getBoolean(getActivity(), cid)) {
                sendMessageToUser();
                PreferencesUtil.putBoolean(getActivity(), cid, true);
            }
        }
    }

    //发送短信
    private void sendMessageToUser() {

        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userId", toUserid);
        params.put("enUserId", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        Call<ApiResponseBody> call = apiservice.sendMessageToUser(params);
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
            }
        });
    }

    private String evaluateId;
    //工程师回复评价
    private void replyEvaluate(String content) {

        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        params.put("targetId", evaluateId);
        params.put("content", content);
        Call<ApiResponseBody> call = apiservice.replyEvaluate(params);
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                mJGPingJia.hideSubmission();
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
            }
        });
    }

    /**
     * 再次咨询
     */
    private void askAgiagn() {
        Intent intent = new Intent(getActivity(), PayActivity.class);
        intent.putExtra("type", mAskType);
        intent.putExtra("eg_user_id", toUserid);
        intent.putExtra("money", mMoney);
        intent.putExtra("name", toChatLocalUsername);
        intent.putExtra("userpic", toHeadImg);
        intent.putExtra("isAgain", 1);
        startActivityForResult(intent, 0x11);

    }


    protected void setUpView() {
        titleBar.setTitle(toChatLocalUsername);

        if (chatType == EaseConstant.CHATTYPE_SINGLE) {
            // set title
            if (EaseUserUtils.getUserInfo(toChatUsername) != null) {
                EaseUser user = EaseUserUtils.getUserInfo(toChatUsername);
                if (user != null) {
                    titleBar.setTitle(user.getNickname());
                    titleBar.setBackgroundColor(Color.parseColor("#2195fc"));
                }
            }

        } else {

            if (chatType == EaseConstant.CHATTYPE_GROUP) {
                //group chat
                EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
                if (group != null)
                    titleBar.setTitle(group.getGroupName());
                // listen the event that user moved out group or group is dismissed
                groupListener = new GroupListener();
                EMClient.getInstance().groupManager().addGroupChangeListener(groupListener);
            } else {
                onChatRoomViewCreation();
            }

        }
        if (chatType != EaseConstant.CHATTYPE_CHATROOM) {
            onConversationInit();
            onMessageListInit();
        }

        titleBar.setLeftLayoutClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        //////////////////////////右上角的结束服务逻辑开始
        if (type == 2) {
            titleBar.setRightText("邀评");
        } else {
            titleBar.setRightText("投诉");
        }
        //新版本要加入投诉工程师功能

//        titleBar.setRightLayoutVisibility(View.GONE);
        //////////////////////////右上角的结束服务逻辑结束
        titleBar.setRightLayoutClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (type == 2) {
                    if (chatType == EaseConstant.CHATTYPE_SINGLE) {
//                    emptyHistory();
                        //这里调用接口结束服务
                        YaoQingPJDialog dialog = new YaoQingPJDialog(new YaoQingPJDialog.onResultCallBack() {
                            @Override
                            public void onCancel() {

                            }

                            @Override
                            public void onSure() {
                                EMMessage message = EMMessage.createTxtSendMessage("您好，如果没有其他问题，请您对我的服务进行评价，评价后对话自动结束。\n【点击本条消息立即评价】", toChatUsername);
                                // 增加自己特定的属性
                                message.setAttribute("invitationEvaluation", true);
                                message.setAttribute("messageCid", cid);
                                sendMessage(message);
                            }
                        });
                        dialog.show(getFragmentManager(), "ConfirmEndChatDialog");
//                    Toast.makeText(getActivity(), "点击了结束任务", Toast.LENGTH_SHORT).show();
                    } else {
                        toGroupDetails();
                    }
                } else {
                   String touSofCid = PreferencesUtil.getString(getActivity(), "touSofCid"+cid);
                    //                跳转投诉页面
                   if(TextUtils.isEmpty(touSofCid)||!touSofCid.equals(cid)){
                       Intent intent = new Intent(getActivity(), ComplaintEngineerActivity.class);
                       intent.putExtra("messageCid", cid);
                       intent.putExtra("eg_user_id", toUserid);
                       intent.putExtra("name", toChatLocalUsername);
                       intent.putExtra("userpic", toHeadImg);

                       startActivity(intent);
                   }else {
                       ToastUtil.showToast(getActivity(),"您已经提交过投诉信息");
                   }
                }


            }
        });

        setRefreshLayoutListener();

        // show forward message if the message is not null
        String forward_msg_id = getArguments().getString("forward_msg_id");
        if (forward_msg_id != null) {
            forwardMessage(forward_msg_id);
        }

    }

    /**
     * 结束咨询
     */
    boolean clickPJITem = true;

    private void endChat() {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        params.put("cid", cid);
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody> call = apiservice.endChat(params);
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                dismissProgress();
                if (response.isSuccessful()) {
                    //结束成功处理
                    clickPJITem = false;
                } else {
                    ToastUtil.showToast(getContext(), response.raw().message());
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                showChatroomToast(apiException.getMessage());
            }
        });
    }

    private void dealEnd() {
        closeInput();
        //展示"服务结束，等待用户打分"
        type = 1;
        titleBar.setRightLayoutVisibility(View.GONE);
        mJGPingJia.setVisibility(View.VISIBLE);
        mJGPingJia.setOnCommitListener(new JGPingJia.onCommit() {
            @Override
            public void onCommit(int i, int j, int k, String content) {
                if (TextUtils.isEmpty(content))
                    content = "用户没有输入任何内容";
                evaluate(i, j, k, content);
            }
        });
    }

    /**
     * register extend menu, item id need > 3 if you override this method and keep exist item
     */
    protected void registerExtendMenuItem() {
        for (int i = 0; i < itemStrings.length; i++) {
            inputMenu.registerExtendMenuItem(itemStrings[i], itemdrawables[i], itemIds[i], extendMenuItemClickListener);
        }
    }


    protected void onConversationInit() {
        conversation = EMClient.getInstance().chatManager().getConversation(toChatUsername, EaseCommonUtils.getConversationType(chatType), true);
        conversation.markAllMessagesAsRead();
        // the number of messages loaded into conversation is getChatOptions().getNumberOfMessagesLoaded
        // you can change this number
        final List<EMMessage> msgs = conversation.getAllMessages();
        int msgCount = msgs != null ? msgs.size() : 0;
        if (msgCount < conversation.getAllMsgCount() && msgCount < pagesize) {
            String msgId = null;
            if (msgs != null && msgs.size() > 0) {
                msgId = msgs.get(0).getMsgId();
            }
            conversation.loadMoreMsgFromDB(msgId, pagesize - msgCount);
        }

    }

    protected void onMessageListInit() {
        messageList.init(toChatUsername, chatType, chatFragmentHelper != null ?
                chatFragmentHelper.onSetCustomChatRowProvider() : null);
        setListItemClickListener();

        messageList.getListView().setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideKeyboard();
                inputMenu.hideExtendMenuContainer();
                return false;
            }
        });

        isMessageListInited = true;
    }

    private void showPOP(View view, final int position) {
//        LinearLayout layout = new LinearLayout(getActivity());
//        layout.setBackgroundColor(Color.GRAY);
////        layout.setBackgroundResource(R.drawable.bg_circle_gray);
//        layout.setGravity(Gravity.CENTER);
//        TextView tv = new TextView(getActivity());
//        tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
//        tv.setText("删除");
//        tv.setTextColor(Color.WHITE);
//        layout.addView(tv);
//        View contentView = LayoutInflater.from(getActivity()).inflate(com.asktgapp.R.layout.pop_delete, null);
//        RelativeLayout delete = contentView.findViewById(com.asktgapp.R.id.bg);
//        PopupWindow popupWindow = new PopupWindow(contentView,contentView.getWidth(),contentView.getHeight());
//
//        popupWindow.setFocusable(true);
//        popupWindow.setOutsideTouchable(true);
//        popupWindow.setBackgroundDrawable(new BitmapDrawable());
//
//        int[] location = new int[2];
//        view.getLocationOnScreen(location);
//
//        popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, location[0], location[1] - popupWindow.getHeight());
        //创建并显示popWindow
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        if (popWindow == null) {
            View contentView = LayoutInflater.from(getActivity()).inflate(com.asktgapp.R.layout.pop_delete, null);
            FrameLayout delete = contentView.findViewById(com.asktgapp.R.id.bg);
            popWindow = new CustomPopWindow.PopupWindowBuilder(getActivity())
                    .setView(contentView)
                    .size(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
                    .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {

                        }
                    })
                    .setTouchable(true)
                    .setOutsideTouchable(true)
                    .create();
            delete.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    popWindow.dissmiss();
                    if (contextMenuMessage == null)
                        return;
                    //删除当前会话的某条聊天记录
                    EMConversation conversation = EMClient.getInstance().chatManager().getConversation(contextMenuMessage.getUserName());
                    conversation.removeMessage(contextMenuMessage.getMsgId());
                    messageList.refreshSeekTo(position);

                }
            });
        }
        popWindow.showAtLocation(view, Gravity.NO_GRAVITY, location[0], location[1] + popWindow.getHeight());
    }

    protected void setListItemClickListener() {
        messageList.setItemClickListener(new EaseChatMessageList.MessageListItemClickListener() {

            @Override
            public void onUserAvatarClick(String username) {
                if (PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER))
                    return;
                if (username.equals(toChatUsername)) {
                    Intent intent = new Intent(getActivity(), EngineerDetailActivity.class);
                    intent.putExtra("id", toUserid);
                    startActivity(intent);
                }
                if (chatFragmentHelper != null) {
                    chatFragmentHelper.onAvatarClick(username);
                }
            }

            @Override
            public void onUserAvatarLongClick(String username) {
                if (chatFragmentHelper != null) {
                    chatFragmentHelper.onAvatarLongClick(username);
                }
            }

            @Override
            public void onMessageInProgress(EMMessage message) {

            }

            @Override
            public boolean onResendClick(final EMMessage message) {
                new EaseAlertDialog(getActivity(), R.string.resend, R.string.confirm_resend, null, new AlertDialogUser() {
                    @Override
                    public void onResult(boolean confirmed, Bundle bundle) {
                        if (!confirmed) {
                            return;
                        }
                        resendMessage(message);

                    }
                }, true).show();
                return true;
            }

            @Override
            public void onBubbleLongClick(EMMessage message, int position, View view) {
                contextMenuMessage = message;
                showPOP(view, position);
                if (chatFragmentHelper != null) {
                    chatFragmentHelper.onMessageBubbleLongClick(message);
                }
            }

            @Override
            public boolean onBubbleClick(EMMessage message) {
                if (type != 2 && message.getBooleanAttribute("invitationEvaluation", false) && clickPJITem) {

                    if (!PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER)
                            &&pingJia.getVisibility()==View.GONE){
                        if(cid.equals(message.getStringAttribute("messageCid","1"))){
                            clickItemYQPJ();
                        }
                    }

                }

                if (chatFragmentHelper == null) {
                    return false;
                }
                return chatFragmentHelper.onMessageBubbleClick(message);
            }

        });
    }

    /**
     * 用户点击邀请评价对话
     */

    private void clickItemYQPJ() {
        ConfirmEndChatDialog dialog = new ConfirmEndChatDialog(new ConfirmEndChatDialog.onResultCallBack() {
            @Override
            public void onCancel() {

            }

            @Override
            public void onSure() {
                dealEnd();
            }
        });
        dialog.show(getFragmentManager(), "ConfirmEndChatDialog");
    }

    protected void setRefreshLayoutListener() {
        swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        if (listView.getFirstVisiblePosition() == 0 && !isloading && haveMoreData) {
                            List<EMMessage> messages;
                            try {
                                if (chatType == EaseConstant.CHATTYPE_SINGLE) {
                                    messages = conversation.loadMoreMsgFromDB(messageList.getItem(0).getMsgId(),
                                            pagesize);
                                } else {
                                    messages = conversation.loadMoreMsgFromDB(messageList.getItem(0).getMsgId(),
                                            pagesize);
                                }
                            } catch (Exception e1) {
                                swipeRefreshLayout.setRefreshing(false);
                                return;
                            }
                            if (messages.size() > 0) {
                                messageList.refreshSeekTo(messages.size() - 1);
                                if (messages.size() != pagesize) {
                                    haveMoreData = false;
                                }
                            } else {
                                haveMoreData = false;
                            }

                            isloading = false;

                        } else {
                            Toast.makeText(getActivity(), getResources().getString(R.string.no_more_messages),
                                    Toast.LENGTH_SHORT).show();
                        }
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }, 600);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE_CAMERA) { // capture new image
                if (cameraFile != null && cameraFile.exists())
                    sendImageMessage(cameraFile.getAbsolutePath());
                onSendMessageListener.onSendPicMessage("[图片]");
                messageResult = "[图片]";
            } else if (requestCode == REQUEST_CODE_LOCAL) { // send local image
                if (data != null) {
                    Uri selectedImage = data.getData();
                    if (selectedImage != null) {
                        sendPicByUri(selectedImage);
                        onSendMessageListener.onSendPicMessage("[图片]");
                        messageResult = "[图片]";
                    }
                }
            } else if (requestCode == REQUEST_CODE_MAP) { // location
                double latitude = data.getDoubleExtra("latitude", 0);
                double longitude = data.getDoubleExtra("longitude", 0);
                String locationAddress = data.getStringExtra("address");
                if (locationAddress != null && !locationAddress.equals("")) {
//                    Toast.makeText(getActivity(), "暂时未集成地图应用", Toast.LENGTH_SHORT).show();
                    sendLocationMessage(latitude, longitude, locationAddress);
                } else {
                    Toast.makeText(getActivity(), R.string.unable_to_get_loaction, Toast.LENGTH_SHORT).show();
                }

            } else if (requestCode == 0x11) {
                //重新咨询
                getActivity().finish();
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        if (isMessageListInited)
            messageList.refresh();
        EaseUI.getInstance().pushActivity(getActivity());
        // register the event listener when enter the foreground
        EMClient.getInstance().chatManager().addMessageListener(this);

        if (chatType == EaseConstant.CHATTYPE_GROUP) {
            EaseAtMessageHelper.get().removeAtMeGroup(toChatUsername);
        }
        EaseUI.getInstance().getNotifier().reset();
    }

    @Override
    public void onStop() {
        super.onStop();
        // unregister this event listener when this activity enters the
        // background
        EMClient.getInstance().chatManager().removeMessageListener(this);

        // remove activity from foreground activity list
        EaseUI.getInstance().popActivity(getActivity());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (groupListener != null) {
            EMClient.getInstance().groupManager().removeGroupChangeListener(groupListener);
        }

        if (chatType == EaseConstant.CHATTYPE_CHATROOM) {
            EMClient.getInstance().chatroomManager().leaveChatRoom(toChatUsername);
        }

        if (chatRoomChangeListener != null) {
            EMClient.getInstance().chatroomManager().removeChatRoomChangeListener(chatRoomChangeListener);
        }

    }

    public void onBackPressed() {
        if (inputMenu.onBackPressed()) {
            getActivity().finish();
            if (chatType == EaseConstant.CHATTYPE_GROUP) {
                EaseAtMessageHelper.get().removeAtMeGroup(toChatUsername);
                EaseAtMessageHelper.get().cleanToAtUserList();
            }
            if (chatType == EaseConstant.CHATTYPE_CHATROOM) {
                EMClient.getInstance().chatroomManager().leaveChatRoom(toChatUsername);
            }
//            if (!PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER)) {
//                Intent intent = new Intent(getActivity(), MainActivity.class);
//                intent.putExtra("flag", 123);
//                startActivity(intent);
//            }
        }
    }


    protected void onChatRoomViewCreation() {
        final ProgressDialog pd = ProgressDialog.show(getActivity(), "", "Joining......");
        EMClient.getInstance().chatroomManager().joinChatRoom(toChatUsername, new EMValueCallBack<EMChatRoom>() {

            @Override
            public void onSuccess(final EMChatRoom value) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (getActivity().isFinishing() || !toChatUsername.equals(value.getId()))
                            return;
                        pd.dismiss();
                        EMChatRoom room = EMClient.getInstance().chatroomManager().getChatRoom(toChatUsername);
                        if (room != null) {
                            titleBar.setTitle(room.getName());
                            EMLog.d(TAG, "join room success : " + room.getName());
                        } else {
                            titleBar.setTitle(toChatUsername);
                        }
                        addChatRoomChangeListenr();
                        onConversationInit();
                        onMessageListInit();
                    }
                });
            }

            @Override
            public void onError(final int error, String errorMsg) {
                // TODO Auto-generated method stub
                EMLog.d(TAG, "join room failure : " + error);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        pd.dismiss();
                    }
                });
                getActivity().finish();
            }
        });
    }


    protected void addChatRoomChangeListenr() {
        chatRoomChangeListener = new EMChatRoomChangeListener() {

            @Override
            public void onChatRoomDestroyed(String roomId, String roomName) {
                if (roomId.equals(toChatUsername)) {
                    showChatroomToast(" room : " + roomId + " with room name : " + roomName + " was destroyed");
                    getActivity().finish();
                }
            }

            @Override
            public void onMemberJoined(String roomId, String participant) {
                showChatroomToast("member : " + participant + " join the room : " + roomId);
            }

            @Override
            public void onMemberExited(String roomId, String roomName, String participant) {
                showChatroomToast("member : " + participant + " leave the room : " + roomId + " room name : " + roomName);
            }

            @Override
            public void onRemovedFromChatRoom(int i, String s, String s1, String s2) {
                if (s.equals(toChatUsername)) {
                    String curUser = EMClient.getInstance().getCurrentUser();
                    if (curUser.equals(s2)) {
                        EMClient.getInstance().chatroomManager().leaveChatRoom(toChatUsername);
                        getActivity().finish();
                    } else {
                        showChatroomToast("member : " + s2 + " was kicked from the room : " + s + " room name : " + s1);
                    }
                }
            }

            @Override
            public void onMuteListAdded(String s, List<String> list, long l) {

            }

            @Override
            public void onMuteListRemoved(String s, List<String> list) {

            }

            @Override
            public void onAdminAdded(String s, String s1) {

            }

            @Override
            public void onAdminRemoved(String s, String s1) {

            }

            @Override
            public void onOwnerChanged(String s, String s1, String s2) {

            }

            @Override
            public void onAnnouncementChanged(String s, String s1) {

            }

//            @Override
//            public void onRemovedFromChatRoom(String roomId, String roomName, String participant) {
//                if (roomId.equals(toChatUsername)) {
//                    String curUser = EMClient.getInstance().getCurrentUser();
//                    if (curUser.equals(participant)) {
//                        EMClient.getInstance().chatroomManager().leaveChatRoom(toChatUsername);
//                        getActivity().finish();
//                    } else {
//                        showChatroomToast("member : " + participant + " was kicked from the room : " + roomId + " room name : " + roomName);
//                    }
//                }
//            }

        };

        EMClient.getInstance().chatroomManager().addChatRoomChangeListener(chatRoomChangeListener);
    }

    protected void showChatroomToast(final String toastContent) {
        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(getActivity(), toastContent, Toast.LENGTH_SHORT).show();
            }
        });
    }

    // implement methods in EMMessageListener
    @Override
    public void onMessageReceived(List<EMMessage> messages) {
        for (EMMessage message : messages) {
            String username = null;
            // group message
            if (message.getChatType() == ChatType.GroupChat || message.getChatType() == ChatType.ChatRoom) {
                username = message.getTo();
            } else {
                // single chat message
                username = message.getFrom();
            }

            // if the message is for current conversation
            if (username.equals(toChatUsername) || message.getTo().equals(toChatUsername)) {
                messageList.refreshSelectLast();
                EaseUI.getInstance().getNotifier().vibrateAndPlayTone(message);
            } else {
                //新环信聊天 状态栏通知
                EaseUI.getInstance().getNotifier().play(message);
            }
        }
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> messages) {
        for (EMMessage msg : messages) {
            if (msg.getType() == EMMessage.Type.CMD) {
                EMCmdMessageBody cmdBody = (EMCmdMessageBody) msg.getBody();
                if (msg.getFrom().equals(toChatUsername)) {
                    //是正在聊天的对面发来的
                    String action = cmdBody.action();
                    if (action.equals("结束")) {
                        //工程师已结束服务 发送的透传，关闭输入框，展示评价框
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), "咨询服务已结束！", Toast.LENGTH_LONG).show();
                                type = 1;
                                getPingJia();
                                closeInput();
                            }
                        });


                    } else if (action.equals("开始")) {
                        getActivity().runOnUiThread(new Runnable() {
                            public void run() {
                                mJGPingJia.setVisibility(View.GONE);
                                mAskAgainTV.setVisibility(View.GONE);
                                mWaitForPJ.setVisibility(View.GONE);
                                titleBar.setRightLayoutVisibility(View.VISIBLE);
                                inputMenu.setVisibility(View.VISIBLE);
                            }
                        });
                    } else if (action.equals("已评价")) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                type = 3;
                                mWaitForPJ.setVisibility(View.VISIBLE);
                                mAskAgainTV.setVisibility(View.GONE);
                                getPingJia();
                            }
                        });

                    }
                }

            }
        }

    }

    @Override
    public void onMessageRead(List<EMMessage> messages) {
        if (isMessageListInited) {
            messageList.refresh();
        }
    }

    @Override
    public void onMessageDelivered(List<EMMessage> messages) {
        if (isMessageListInited) {
            messageList.refresh();
        }
    }

    @Override
    public void onMessageRecalled(List<EMMessage> list) {

    }

    @Override
    public void onMessageChanged(EMMessage emMessage, Object change) {
        if (isMessageListInited) {
            messageList.refresh();
        }
    }


    /**
     * handle the click event for extend menu
     */
    class MyItemClickListener implements EaseChatExtendMenu.EaseChatExtendMenuItemClickListener {

        @Override
        public void onClick(int itemId, View view) {
            if (chatFragmentHelper != null) {
                if (chatFragmentHelper.onExtendMenuItemClick(itemId, view)) {
                    return;
                }
            }
            switch (itemId) {
                case ITEM_TAKE_PICTURE:
                    selectPicFromCamera(getActivity());
                    break;
                case ITEM_PICTURE:
                    selectPicFromLocal(getActivity());
                    break;
                case ITEM_LOCATION:
                    startActivityForResult(new Intent(getActivity(), EaseBaiduMapActivity.class), REQUEST_CODE_MAP);
                    break;
                case ITEM_VIDEO:
//                    Intent intent = new Intent(getActivity(), ImageGridActivity.class);
//                    startActivityForResult(intent, REQUEST_CODE_SELECT_VIDEO);
                    break;
                default:
                    break;
            }
        }

    }

    /**
     * input @
     *
     * @param username
     */
    protected void inputAtUsername(String username, boolean autoAddAtSymbol) {
        if (EMClient.getInstance().getCurrentUser().equals(username) ||
                chatType != EaseConstant.CHATTYPE_GROUP) {
            return;
        }
        EaseAtMessageHelper.get().addAtUser(username);
        EaseUser user = EaseUserUtils.getUserInfo(username);
        if (user != null) {
            username = user.getNickname();
        }
        if (autoAddAtSymbol)
            inputMenu.insertText("@" + username + " ");
        else
            inputMenu.insertText(username + " ");
    }


    /**
     * input @
     *
     * @param username
     */
    protected void inputAtUsername(String username) {
        inputAtUsername(username, true);
    }


    //send message
    protected void sendTextMessage(String content) {
        messageHasSendCur = content;
        sendSMS();
        if (EaseAtMessageHelper.get().containsAtUsername(content)) {
            sendAtMessage(content);
        } else {
            EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
            sendMessage(message);
        }
    }

    /**
     * send @ message, only support group chat message
     *
     * @param content
     */
    @SuppressWarnings("ConstantConditions")
    private void sendAtMessage(String content) {
        if (chatType != EaseConstant.CHATTYPE_GROUP) {
            EMLog.e(TAG, "only support group chat message");
            return;
        }
        EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
        EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
        if (EMClient.getInstance().getCurrentUser().equals(group.getOwner()) && EaseAtMessageHelper.get().containsAtAll(content)) {
            message.setAttribute(EaseConstant.MESSAGE_ATTR_AT_MSG, EaseConstant.MESSAGE_ATTR_VALUE_AT_MSG_ALL);
        } else {
            message.setAttribute(EaseConstant.MESSAGE_ATTR_AT_MSG,
                    EaseAtMessageHelper.get().atListToJsonArray(EaseAtMessageHelper.get().getAtMessageUsernames(content)));
        }
        sendMessage(message);

    }


    protected void sendBigExpressionMessage(String name, String identityCode) {
        messageHasSendCur = "表情消息";
        EMMessage message = EaseCommonUtils.createExpressionMessage(toChatUsername, name, identityCode);
        sendMessage(message);
    }

    protected void sendVoiceMessage(String filePath, int length) {
        messageHasSendCur = "声音消息";
        sendSMS();
        EMMessage message = EMMessage.createVoiceSendMessage(filePath, length, toChatUsername);
        sendMessage(message);
    }

    protected void sendImageMessage(String imagePath) {
        messageHasSendCur = "图像消息";
        sendSMS();
        EMMessage message = EMMessage.createImageSendMessage(imagePath, false, toChatUsername);
        sendMessage(message);
    }

    protected void sendLocationMessage(double latitude, double longitude, String locationAddress) {
        messageHasSendCur = "地理消息";
        EMMessage message = EMMessage.createLocationSendMessage(latitude, longitude, locationAddress, toChatUsername);
        sendMessage(message);
    }

    protected void sendVideoMessage(String videoPath, String thumbPath, int videoLength) {
        messageHasSendCur = "视频消息";
        EMMessage message = EMMessage.createVideoSendMessage(videoPath, thumbPath, videoLength, toChatUsername);
        sendMessage(message);
    }

    protected void sendFileMessage(String filePath) {
        messageHasSendCur = "文件消息";

        EMMessage message = EMMessage.createFileSendMessage(filePath, toChatUsername);
        sendMessage(message);
    }


    protected void sendMessage(EMMessage message) {
        if (message == null) {
            return;
        }
        message.setAttribute("nickName", PreferencesUtil.getString(getActivity(), PreferencesUtil.KEY_NAME) + "");
        if (chatFragmentHelper != null) {
            //set extension
            chatFragmentHelper.onSetMessageAttributes(message);
        }
        if (chatType == EaseConstant.CHATTYPE_GROUP) {
            message.setChatType(ChatType.GroupChat);
        } else if (chatType == EaseConstant.CHATTYPE_CHATROOM) {
            message.setChatType(ChatType.ChatRoom);
        }
        //send message
        EMClient.getInstance().chatManager().sendMessage(message);
        //refresh ui
        if (isMessageListInited) {
            messageList.refreshSelectLast();
        }
    }


    public void resendMessage(EMMessage message) {
        message.setStatus(EMMessage.Status.CREATE);
        message.setAttribute("nickName", PreferencesUtil.getString(getActivity(), PreferencesUtil.KEY_NAME) + "");
        EMClient.getInstance().chatManager().sendMessage(message);
        messageList.refresh();
    }

    //===================================================================================


    /**
     * send image
     *
     * @param selectedImage
     */
    protected void sendPicByUri(Uri selectedImage) {
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            cursor = null;

            if (picturePath == null || picturePath.equals("null")) {
                Toast toast = Toast.makeText(getActivity(), R.string.cant_find_pictures, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;
            }
            sendImageMessage(picturePath);
        } else {
            File file = new File(selectedImage.getPath());
            if (!file.exists()) {
                Toast toast = Toast.makeText(getActivity(), R.string.cant_find_pictures, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;

            }
            sendImageMessage(file.getAbsolutePath());
        }

    }

    /**
     * send file
     *
     * @param uri
     */
    protected void sendFileByUri(Uri uri) {
        String filePath = null;
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = null;

            try {
                cursor = getActivity().getContentResolver().query(uri, filePathColumn, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    filePath = cursor.getString(column_index);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            filePath = uri.getPath();
        }
        if (filePath == null) {
            return;
        }
        File file = new File(filePath);
        if (!file.exists()) {
            Toast.makeText(getActivity(), R.string.File_does_not_exist, Toast.LENGTH_SHORT).show();
            return;
        }
        //limit the size < 10M
        if (file.length() > 10 * 1024 * 1024) {
            Toast.makeText(getActivity(), R.string.The_file_is_not_greater_than_10_m, Toast.LENGTH_SHORT).show();
            return;
        }
        sendFileMessage(filePath);
    }

    /**
     * capture new image
     *
     * @param activity
     */
    protected void selectPicFromCamera(FragmentActivity activity) {
        if (!EaseCommonUtils.isSdcardExist()) {
            Toast.makeText(getActivity(), R.string.sd_card_does_not_exist, Toast.LENGTH_SHORT).show();
            return;
        }

        cameraFile = new File(PathUtil.getInstance().getImagePath(), EMClient.getInstance().getCurrentUser()
                + System.currentTimeMillis() + ".jpg");
        //noinspection ResultOfMethodCallIgnored
        cameraFile.getParentFile().mkdirs();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // TODO: 2018/3/6 这里要替换
            Uri imageUri = FileProvider.getUriForFile(activity, "com.asktgapp.fileprovider", cameraFile);
//            Uri imageUri = FileProvider.getUriForFile(activity, "com.biu.fm.fileprovider", cameraFile);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//这里加入flag
            startActivityForResult(intent, REQUEST_CODE_CAMERA);
        } else {
            startActivityForResult(
                    new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
                    REQUEST_CODE_CAMERA);
        }
    }

    /**
     * select local image
     *
     * @param activity
     */
    protected void selectPicFromLocal(FragmentActivity activity) {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");

        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_LOCAL);
    }


    /**
     * clear the conversation history
     */
    protected void emptyHistory() {
        String msg = getResources().getString(R.string.Whether_to_empty_all_chats);
        new EaseAlertDialog(getActivity(), null, msg, null, new AlertDialogUser() {

            @Override
            public void onResult(boolean confirmed, Bundle bundle) {
                if (confirmed) {
                    EMClient.getInstance().chatManager().deleteConversation(toChatUsername, true);
                    messageList.refresh();
                }
            }
        }, true).show();
    }

    /**
     * open group detail
     */
    protected void toGroupDetails() {
        if (chatType == EaseConstant.CHATTYPE_GROUP) {
            EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
            if (group == null) {
                Toast.makeText(getActivity(), R.string.gorup_not_found, Toast.LENGTH_SHORT).show();
                return;
            }
            if (chatFragmentHelper != null) {
                chatFragmentHelper.onEnterToChatDetails();
            }
        } else if (chatType == EaseConstant.CHATTYPE_CHATROOM) {
            if (chatFragmentHelper != null) {
                chatFragmentHelper.onEnterToChatDetails();
            }
        }
    }

    /**
     * hide
     */
    protected void hideKeyboard() {
        if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getActivity().getCurrentFocus() != null)
                inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * forward message
     *
     * @param forward_msg_id
     */
    protected void forwardMessage(String forward_msg_id) {
        final EMMessage forward_msg = EMClient.getInstance().chatManager().getMessage(forward_msg_id);
        EMMessage.Type type = forward_msg.getType();
        switch (type) {
            case TXT:
                if (forward_msg.getBooleanAttribute(EaseConstant.MESSAGE_ATTR_IS_BIG_EXPRESSION, false)) {
                    sendBigExpressionMessage(((EMTextMessageBody) forward_msg.getBody()).getMessage(),
                            forward_msg.getStringAttribute(EaseConstant.MESSAGE_ATTR_EXPRESSION_ID, null));
                } else {
                    // get the content and send it
                    String content = ((EMTextMessageBody) forward_msg.getBody()).getMessage();
                    sendTextMessage(content);
                }
                break;
            case IMAGE:
                // send image
                String filePath = ((EMImageMessageBody) forward_msg.getBody()).getLocalUrl();
                if (filePath != null) {
                    File file = new File(filePath);
                    if (!file.exists()) {
                        // send thumb nail if original image does not exist
                        filePath = ((EMImageMessageBody) forward_msg.getBody()).thumbnailLocalPath();
                    }
                    sendImageMessage(filePath);
                }
                break;
            default:
                break;
        }

        if (forward_msg.getChatType() == ChatType.ChatRoom) {
            EMClient.getInstance().chatroomManager().leaveChatRoom(forward_msg.getTo());
        }
    }

    /**
     * listen the group event
     */
    class GroupListener extends EaseGroupRemoveListener {

        @Override
        public void onUserRemoved(final String groupId, String groupName) {
            getActivity().runOnUiThread(new Runnable() {

                public void run() {
                    if (toChatUsername.equals(groupId)) {
                        Toast.makeText(getActivity(), R.string.you_are_group, Toast.LENGTH_LONG).show();
                        Activity activity = getActivity();
                        if (activity != null && !activity.isFinishing()) {
                            activity.finish();
                        }
                    }
                }
            });
        }

        @Override
        public void onGroupDestroyed(final String groupId, String groupName) {
            // prompt group is dismissed and finish this activity
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    if (toChatUsername.equals(groupId)) {
                        Toast.makeText(getActivity(), R.string.the_current_group_destroyed, Toast.LENGTH_LONG).show();
                        Activity activity = getActivity();
                        if (activity != null && !activity.isFinishing()) {
                            activity.finish();
                        }
                    }
                }
            });
        }

        @Override
        public void onAnnouncementChanged(String s, String s1) {

        }

        @Override
        public void onSharedFileAdded(String s, EMMucSharedFile emMucSharedFile) {

        }

        @Override
        public void onSharedFileDeleted(String s, String s1) {

        }

    }


    protected EaseChatFragmentHelper chatFragmentHelper;

    public void setChatFragmentListener(EaseChatFragmentHelper chatFragmentHelper) {
        this.chatFragmentHelper = chatFragmentHelper;
    }

    public interface EaseChatFragmentHelper {
        /**
         * set message attribute
         */
        void onSetMessageAttributes(EMMessage message);

        /**
         * enter to chat detail
         */
        void onEnterToChatDetails();

        /**
         * on avatar clicked
         *
         * @param username
         */
        void onAvatarClick(String username);

        /**
         * on avatar long pressed
         *
         * @param username
         */
        void onAvatarLongClick(String username);

        /**
         * on message bubble clicked
         */
        boolean onMessageBubbleClick(EMMessage message);

        /**
         * on message bubble long pressed
         */
        void onMessageBubbleLongClick(EMMessage message);

        /**
         * on extend menu item clicked, return true if you want to override
         *
         * @param view
         * @param itemId
         * @return
         */
        boolean onExtendMenuItemClick(int itemId, View view);

        /**
         * on set custom chat row provider
         *
         * @return
         */
        EaseCustomChatRowProvider onSetCustomChatRowProvider();
    }


    public interface OnSendMessageListener {
        void onSendTextMessage(String content);

        void onSendVoiceMessage(String content);

        void onSendPicMessage(String content);

        void onSendBigEmoj(String content);
    }


    /**
     * 隐藏progress loading
     */
    public void dismissProgress() {
        FragmentManager fm = getChildFragmentManager();
        LoadingDialogFragment loading = (LoadingDialogFragment) fm.findFragmentByTag("loading");
        if (loading != null) {
            loading.dismiss();
        }
    }

    /**
     * 显示progress loading
     * 进行操作需请求网络时显示  如 登录 注册...
     *
     * @param requestTag 网络请求tag，用于取消请求
     */
    public void showProgress(String requestTag) {
        LoadingDialogFragment loading = LoadingDialogFragment.newInstance(DialogFragment.STYLE_NO_TITLE, com.asktgapp.modulebase.R.layout.loading, requestTag);
        FragmentTransaction ft = getChildFragmentManager().beginTransaction();
        ft.addToBackStack(null);
        loading.show(ft, "loading");
    }
}
